package com.freemypay.java.十二通过异常处理错误.十构造器;

/**
 * Each disposable object must be followed a tyr-finally
 * 每个需要被清理的对象都必须跟随一个try-finally
 * @author yesixian
 * @date 2018年7月20日
 */
public class CleanupIdiom {
	public static void main(String[] args) {
		// Section 1;
		NeedsCleanup nc1 = new NeedsCleanup();
		
		try {
			// ...
		} finally {
			// TODO: handle finally clause
			nc1.dispose();
		}
		
		// Section 2;
		// If construction cannot fail you can group objects;
		NeedsCleanup nc2 = new NeedsCleanup();
		NeedsCleanup nc3 = new NeedsCleanup();
		try {
			// ...
		} finally {
			// TODO: handle finally clause
			nc3.dispose(); // Reverse order of construction
			nc2.dispose();
		}
		
		// Section 3;
		// If construction can fail you must guard(保护) each one;
		try {
			NeedsCleanup2 nc4 = new NeedsCleanup2();
			try {
				NeedsCleanup2 nc5 = new NeedsCleanup2();
				try {
					// ...
				} finally {
					// TODO: handle finally clause
					nc5.dispose();
				}
			} catch (ConstructionException e) { // nc5 constructor
				// TODO: handle exception
				System.out.println(e);
			} finally {
				nc4.dispose();
			}
		} catch (ConstructionException e) { // nc4 constructor
			// TODO Auto-generated catch block
			System.out.println(e);
		}
		
	}
}

class NeedsCleanup { // Construction can't fail
	private static long counter = 1;
	private final long id = counter++;
	
	public void dispose() {
		System.out.println("NeedsCleanup " + id + " disposed");
	}
}

class ConstructionException extends Exception {}

class NeedsCleanup2 extends NeedsCleanup {
	// Construction can fail;
	public NeedsCleanup2() throws ConstructionException {}
}

